﻿using System;
using System.Text;

namespace MyFastORM
{
    /// <summary>
    /// 快速ORM框架内部使用的C#代码生成器
    /// </summary>
    internal class MyFastORMCodeGenerater
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        public MyFastORMCodeGenerater()
        {
        }

        private MyFastORMFramework myFramework = null;
        /// <summary>
        /// ORM框架对象
        /// </summary>
        public MyFastORMFramework Framework
        {
            get
            {
                return myFramework;
            }
            set
            {
                myFramework = value;
            }
        }

        /// <summary>
        /// 代码生成过程
        /// </summary>
        /// <param name="nsName">名称空间名称</param>
        /// <param name="strFileName">保存代码文本的文件名</param>
        /// <param name="RecordTypes">要处理的数据库实体对象类型</param>
        /// <returns>生成的完整的可编译的C#代码文本</returns>
        public string GenerateCode(
            string nsName,
            string strFileName,
            System.Collections.ArrayList RecordTypes)
        {
            // 开始输出C#代码文本
            IndentTextWriter myWriter = new IndentTextWriter();
            myWriter.WriteLine("using System;");
            myWriter.WriteLine("using System.Data;");
            myWriter.WriteLine("namespace " + nsName);
            myWriter.BeginGroup("{");
            // 对每一个数据容器对象创建数据处理类的代码
            foreach (Type RecordType in RecordTypes)
            {
                // 对象操作的数据表的名称
                string TableName = RecordType.Name;
                // 获得ORM绑定信息
                BindTableAttribute ta = (BindTableAttribute)Attribute.GetCustomAttribute(
                    RecordType, typeof(BindTableAttribute), false);
                if (ta != null)
                {
                    TableName = ta.Name;
                }
                if (TableName == null || TableName.Trim().Length == 0)
                {
                    TableName = RecordType.Name;
                }
                TableName = TableName.Trim();
                //获得对象类型中所有的具有ORM特性的成员属性
                System.Reflection.PropertyInfo[] ps = this.myFramework.GetBindProperties(RecordType);
                // 开始为对象类型输出C#源代码文本
                // 例如输出 public class DB_EmployeesORMHelper : MyFastORM.RecordORMHelper
                myWriter.WriteLine("public class " + RecordType.Name + "ORMHelper : " + typeof(RecordORMHelper).FullName);
                myWriter.BeginGroup("{");
                myWriter.WriteLine("");
                myWriter.WriteLine("///<summary>创建对象</summary>");
                myWriter.WriteLine("public " + RecordType.Name + "ORMHelper(){}");
                myWriter.WriteLine("");


                // 重载 RecordORMHelper类型的TableName属性，返回对象操作的数据表的名称
                myWriter.WriteLine("public override string TableName");
                myWriter.BeginGroup("{");
                if (TableName == null)
                {
                    myWriter.WriteLine("get{ return null;}");
                }
                else
                {
                    myWriter.WriteLine("get{ return \"" + TableName + "\" ;}");
                }
                myWriter.EndGroup("}");
                myWriter.WriteLine("");
                // 生成对象操作的所有的数据库字段名称的数组
                // 这里生成以下样式的源代码文本
                // private static string[] myRecordFieldNames = new string[]
                //       { "字段名1" , "字段2" , "字段3" };
                myWriter.WriteLine("private static string[] myRecordFieldNames = new string[]");
                myWriter.IncreaseIndent();
                myWriter.BeginGroup("{");
                for (int iCount = 0; iCount < ps.Length; iCount++)
                {
                    System.Reflection.PropertyInfo p = ps[iCount];
                    // 获得对象类型成员属性映射的数据库字段名
                    string name = GetBindFieldName(p);
                    if (iCount != ps.Length - 1)
                        myWriter.WriteLine("\"" + name + "\",");
                    else
                        myWriter.WriteLine("\"" + name + "\"");
                }
                myWriter.EndGroup("};");
                myWriter.DecreaseIndent();
                // 生成重载 RecordFieldNames 属性的源代码
                myWriter.WriteLine("///<summary>字段名列表</summary>");
                myWriter.WriteLine("protected override string[] RecordFieldNames");
                myWriter.BeginGroup("{");
                myWriter.WriteLine("get");
                myWriter.BeginGroup("{");
                myWriter.WriteLine("return myRecordFieldNames ;");
                myWriter.EndGroup("}");
                myWriter.EndGroup("}");

                #region 开始输出重载 InnerReadRecord函数的C#代码文本

                // 开始输出重载 InnerReadRecord函数的C#代码文本
                myWriter.WriteLine("// 从数据读取器读取数据创建对象");
                myWriter.WriteLine("protected override object InnerReadRecord( System.Data.IDataReader reader , int[] FieldIndexs )");
                myWriter.BeginGroup("{");
                // 输出创建对象实例的C#代码文本
                myWriter.WriteLine(RecordType.FullName + " record = new " + RecordType.FullName + "();");
                myWriter.WriteLine("int index = 0 ;");
                // 获得类型中绑定到数据库的属性信息
                for (int iCount = 0; iCount < ps.Length; iCount++)
                {
                    System.Reflection.PropertyInfo p = ps[iCount];
                    if (p.CanWrite == false)
                    {
                        continue;
                    }

                    BindFieldAttribute fa = (BindFieldAttribute)Attribute.GetCustomAttribute(
                        p, typeof(BindFieldAttribute));

                    myWriter.WriteLine("");
                    myWriter.WriteLine("index = FieldIndexs[ " + iCount + " ]; // 读取字段 " + GetBindFieldName(p));
                    myWriter.WriteLine("if( index >= 0 )");
                    myWriter.BeginGroup("{");
                    // 获得属性数据类型
                    Type pt = p.PropertyType;
                    // 获得属性默认值
                    object DefaultValue = this.GetDefaultValue(p);
                    string strRead = null;
                    // 以下根据属性数据类型的不同而调用父类的ConvertTo*函数来读取数据并进行数据类型的转换
                    if (pt.Equals(typeof(byte)))
                    {
                        // 读取字节数据
                        strRead = "ConvertToByte( reader.GetValue( index ) , ( byte ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(sbyte)))
                    {
                        // 读取带符号字节数据
                        strRead = "ConvertToSByte( reader.GetValue( index ) , ( sbyte ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(short)))
                    {
                        // 读取短整数
                        strRead = "ConvertToInt16( reader.GetValue( index ) , ( short ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(ushort)))
                    {
                        // 读取无符号短整数
                        strRead = "ConvertToUInt16( reader.GetValue( index ) , ( ushort ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(int)))
                    {
                        // 读取整数
                        strRead = "ConvertToInt32( reader.GetValue( index ) , ( int ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(uint)))
                    {
                        // 读取无符号短整数
                        strRead = "ConvertToUInt32( reader.GetValue( index ) , ( uint ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(long)))
                    {
                        // 读取长整数
                        strRead = "ConvertToInt64( reader.GetValue( index ) , ( long ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(ulong)))
                    {
                        // 读取无符号长整数
                        strRead = "ConvertToUInt64( reader.GetValue( index ) , ( ulong ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(decimal)))
                    {
                        // 读取小数
                        strRead = "ConvertToDecimal( reader.GetValue( index ) , ( deciaml ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(float)))
                    {
                        // 读取单精度浮点数
                        strRead = "ConvertToSingle( reader.GetValue( index ) , ( float ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(double)))
                    {
                        // 读取双精度浮点数
                        strRead = "ConvertToDouble( reader.GetValue( index ) , ( double ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(DateTime)))
                    {
                        // 读取时间数据，这里使用了属性ORM绑定信息中的ReadFormat参数
                        string strDefault = "DateTime.MinValue";
                        DateTime dt = Convert.ToDateTime(DefaultValue);
                        if (dt.Equals(DateTime.MinValue) == false)
                        {
                            strDefault = "new DateTime( " + dt.Ticks + ")";
                        }
                        strRead = "ConvertToDateTime( reader.GetValue( index ) , " + strDefault + " , " + (fa.ReadFormat == null ? "null" : "\"" + fa.ReadFormat + "\"") + " )";
                    }
                    else if (pt.Equals(typeof(string)))
                    {
                        // 读取字符串数据
                        strRead = "ConvertToString( reader.GetValue( index ) , " + (DefaultValue == null ? "null" : "@\"" + DefaultValue.ToString() + "\"") + " )";
                    }
                    else if (pt.Equals(typeof(char)))
                    {
                        // 读取单个字符
                        strRead = "ConvertToChar( reader.GetValue( index ) , ( char ) " + DefaultValue + " )";
                    }
                    else if (pt.Equals(typeof(byte[])))
                    {
                        // 读取字节数组
                        strRead = "( byte[] ) ( reader.GetValue( index ) )";
                    }
                    else
                    {
                        // 其他数据类型不支持
                        throw new InvalidOperationException("不支持属性类型" + p.Name + " " + pt.FullName);
                    }
                    // 输出设置对象属性值的C#代码
                    myWriter.WriteLine("record." + p.Name + " = " + strRead + " ;");
                    myWriter.EndGroup("}");
                }//for

                myWriter.WriteLine("");
                myWriter.WriteLine("return record ;");
                myWriter.EndGroup("}//InnerReadRecord");
                // 结束输出重载 InnerReadRecord 的C#代码

                #endregion


                #region 输出重载FillInsertCommand函数的源代码

                // 输出重载FillInsertCommand函数的源代码
                myWriter.WriteLine("");
                myWriter.WriteLine("///<summary>初始化插入记录使用的命令对象</summary>");
                myWriter.WriteLine("public override int FillInsertCommand( System.Data.IDbCommand cmd , object objRecord )");
                myWriter.BeginGroup("{");
                // 输出检查参数的源代码
                myWriter.WriteLine("if( cmd == null ) throw new ArgumentNullException(\"cmd\");");
                myWriter.WriteLine("if( objRecord == null ) throw new ArgumentNullException(\"objRecord\");");
                myWriter.WriteLine(RecordType.FullName + " myRecord = objRecord as " + RecordType.FullName + " ;");
                myWriter.WriteLine("if( myRecord == null ) throw new ArgumentException(\"must type '" + RecordType.FullName + "' \");");
                // myFieldNames 列表将放置数据库字段名
                myWriter.WriteLine("System.Collections.ArrayList myFieldNames = new System.Collections.ArrayList();");
                // myValues 列表将放置属性值
                myWriter.WriteLine("System.Collections.ArrayList myValues = new System.Collections.ArrayList();");
                for (int iCount = 0; iCount < ps.Length; iCount++)
                {
                    System.Reflection.PropertyInfo p = ps[iCount];
                    if (p.CanRead == false)
                    {
                        continue;
                    }

                    BindFieldAttribute fa = (BindFieldAttribute)Attribute.GetCustomAttribute(
                        p, typeof(BindFieldAttribute));
                    string FieldName = GetBindFieldName(p);

                    myWriter.WriteLine("");
                    Type pt = p.PropertyType;
                    // 获得属性的默认值
                    object DefaultValue = GetDefaultValue(p);
                    if (pt.Equals(typeof(string)))
                    {
                        // 处理字符串类型的属性
                        myWriter.WriteLine("if( myRecord." + p.Name + " != null && myRecord." + p.Name + ".Length != 0 )");
                        myWriter.BeginGroup("{");
                        // 若属性字符串值不为空则输出数据库字段名和属性值
                        myWriter.WriteLine("myFieldNames.Add( \"" + FieldName + "\" );");
                        myWriter.WriteLine("myValues.Add( myRecord." + p.Name + " );");
                        myWriter.EndGroup("}");
                    }
                    else if (pt.Equals(typeof(DateTime)))
                    {
                        // 若为属性数值为时间类型则要考虑到ORM绑定信息中的WriteFormat值
                        myWriter.WriteLine("myFieldNames.Add( \"" + FieldName + "\" );");
                        if (fa.WriteFormat != null && fa.WriteFormat.Length > 0)
                        {
                            myWriter.WriteLine("myValues.Add( myRecord." + p.Name
                                + ".ToString(\"" + fa.WriteFormat + "\") );");
                        }
                        else
                        {
                            myWriter.WriteLine("myValues.Add( myRecord." + p.Name
                                + ".ToString(\"yyyy-MM-dd HH:mm:ss\") );");
                        }

                    }
                    else
                    {
                        // 若为其他类型则直接输出字段名和属性值
                        myWriter.WriteLine("myFieldNames.Add( \"" + FieldName + "\" );");
                        myWriter.WriteLine("myValues.Add( myRecord." + p.Name + " );");
                    }
                }//for
                myWriter.WriteLine("");
                myWriter.WriteLine("if( myFieldNames.Count == 0 ) return 0 ;");
                myWriter.WriteLine("cmd.Parameters.Clear() ;");
                // 输出拼凑出新增数据使用的SQL文本
                myWriter.WriteLine("System.Text.StringBuilder mySQL = new System.Text.StringBuilder();");
                myWriter.WriteLine("mySQL.Append( \"Insert Into " + TableName + " ( \" );");
                // 这里调用了父类的 ConcatStrings 函数
                myWriter.WriteLine("mySQL.Append( ConcatStrings( myFieldNames ));");
                myWriter.WriteLine("mySQL.Append( \" ) Values ( \" );");
                myWriter.WriteLine("for( int iCount = 0 ; iCount < myValues.Count ; iCount ++ )");
                myWriter.BeginGroup("{");
                myWriter.WriteLine("if( iCount > 0 ) mySQL.Append(\" , \" );");
                if (myFramework.NamedParameter)
                {
                    // 输出命名SQL参数代码文本
                    myWriter.WriteLine("mySQL.Append(\" @Value\" + iCount ) ;");
                    myWriter.WriteLine("System.Data.IDbDataParameter parameter = cmd.CreateParameter();");
                    myWriter.WriteLine("parameter.Value = myValues[ iCount ] ;");
                    myWriter.WriteLine("parameter.ParameterName = \"Value\" + iCount ;");
                    myWriter.WriteLine("cmd.Parameters.Add( parameter );");
                }
                else
                {
                    // 输入无名称SQL参数代码文本
                    myWriter.WriteLine("mySQL.Append(\" ? \") ;");
                    myWriter.WriteLine("System.Data.IDbDataParameter parameter = cmd.CreateParameter();");
                    myWriter.WriteLine("parameter.Value = myValues[ iCount ] ;");
                    myWriter.WriteLine("cmd.Parameters.Add( parameter );");
                }
                myWriter.EndGroup("}//for");
                myWriter.WriteLine("mySQL.Append( \" ) \" );");
                // 设置SQL文本
                myWriter.WriteLine("cmd.CommandText = mySQL.ToString();");
                myWriter.WriteLine("return myValues.Count ;");
                myWriter.EndGroup("}//public override int FillInsertCommand( System.Data.IDbCommand cmd , object objRecord )");
                // 完成输出重载FillInsertCommand函数的C#代码文本
                myWriter.WriteLine("");

                #endregion

                #region 获取删除或者更新时用的Where子语句和关键字段属性对象

                // 获取删除或者更新时用的Where子语句和关键字段属性对象

                // 关键字段SQL参数名称列表
                System.Collections.ArrayList KeyParameterNames = new System.Collections.ArrayList();
                // 生成以下样式的字符串
                // Where 关键字段名1=? and 关键字段名2=? 
                System.Text.StringBuilder myWhereSQL = new System.Text.StringBuilder();
                System.Collections.ArrayList KeyProperties = new System.Collections.ArrayList();
                for (int iCount = 0; iCount < ps.Length; iCount++)
                {
                    System.Reflection.PropertyInfo p = ps[iCount];
                    if (p.CanRead == false)
                    {
                        continue;
                    }
                    BindFieldAttribute fa = (BindFieldAttribute)Attribute.GetCustomAttribute(
                        p, typeof(BindFieldAttribute));
                    if (fa.Key == false)
                    {
                        // 若不是关键字段则处理下一个属性
                        continue;
                    }
                    // 获得属性映射的数据库字段名
                    string FieldName = GetBindFieldName(p);
                    if (myWhereSQL.Length > 0)
                    {
                        myWhereSQL.Append(" and ");
                    }
                    KeyProperties.Add(p);
                    if (myFramework.NamedParameter)
                    {
                        // 若采用命名参数模式则输出“字段名 = @Key属性名称 ”
                        string pName = "Key" + p.Name;
                        KeyParameterNames.Add(pName);
                        myWhereSQL.Append(myFramework.FixFieldName(FieldName) + " = @" + pName + " ");
                    }
                    else
                    {
                        // 若采用匿名参数模式则输出“字段名 = ?”
                        myWhereSQL.Append(myFramework.FixFieldName(FieldName) + " = ? ");
                    }
                }//for
                // 经过循环处理后,myWhereSQL的内容就成为“字段名1=? and 字段名2=?”。
                #endregion


                #region 输出重载FillDeleteCommand函数的源代码

                // 输出重载FillDeleteCommand函数的源代码
                myWriter.WriteLine("");
                myWriter.WriteLine("///<summary>初始化删除对象使用的命令对象</summary>");
                myWriter.WriteLine("public override int FillDeleteCommand( System.Data.IDbCommand cmd , object objRecord )");
                myWriter.BeginGroup("{");
                if (KeyProperties.Count == 0)
                {
                    // 若对象类型没有关键属性则直接抛出不支持该方法的异常
                    myWriter.WriteLine("throw new NotSupportedException(\"FillDeleteCommand\");");
                }
                else
                {
                    // 输出检查参数的源代码
                    myWriter.WriteLine("if( cmd == null ) throw new ArgumentNullException(\"cmd\");");
                    myWriter.WriteLine("if( objRecord == null ) throw new ArgumentNullException(\"objRecord\");");
                    myWriter.WriteLine(RecordType.FullName + " myRecord = objRecord as " + RecordType.FullName + " ;");
                    myWriter.WriteLine("if( myRecord == null ) throw new ArgumentException(\"must type '" + RecordType.FullName + "' \");");
                    System.Text.StringBuilder myDeleteSQL = new System.Text.StringBuilder();
                    // 生成类似“Delete From 数据表名 where 查询条件”的文本
                    myDeleteSQL.Insert(0, "Delete From " + TableName + " Where " + myWhereSQL.ToString());
                    // 输出设置SQL命令对象的源代码
                    myWriter.WriteLine("cmd.Parameters.Clear();");
                    myWriter.WriteLine("cmd.CommandText = @\"" + myDeleteSQL.ToString() + "\" ;");
                    myWriter.WriteLine("System.Data.IDbDataParameter parameter = null ;");
                    // 输出填充SQL命令对象参数列表的源代码
                    int index = 0;
                    foreach (System.Reflection.PropertyInfo p in KeyProperties)
                    {
                        myWriter.WriteLine("");
                        myWriter.WriteLine("parameter = cmd.CreateParameter();");
                        WriteSetParameterValue(p, myWriter);
                        if (myFramework.NamedParameter)
                        {
                            // 若使用命名参数则设置SQL命令参数对象的名称
                            myWriter.WriteLine("parameter.ParameterName = \"" + KeyParameterNames[index] + "\";");
                        }
                        myWriter.WriteLine("cmd.Parameters.Add( parameter );");
                        index++;
                    }
                    myWriter.WriteLine("");
                    myWriter.WriteLine("return " + KeyProperties.Count + " ;");
                }
                myWriter.EndGroup("}");
                // 结束输出重载 FillDeleteCommand 函数的源代码

                #endregion

                #region 输出重载 FillUpdateCommand 函数的程序源代码文本


                // 输出重载 FillUpdateCommand 函数的程序源代码文本
                myWriter.WriteLine("///<summary>初始化更新对象使用的命令对象</summary>");
                myWriter.WriteLine("public override int FillUpdateCommand( System.Data.IDbCommand cmd , object objRecord )");
                myWriter.BeginGroup("{");
                if (KeyProperties.Count == 0)
                {
                    // 若没有定义任何关键字段的属性则直接抛出不支持该方法的异常
                    myWriter.WriteLine("throw new NotSupportedException(\"FillUpdateCommand\");");
                }
                else
                {
                    // 输出检查参数的源代码文本
                    myWriter.WriteLine("if( cmd == null ) throw new ArgumentNullException(\"cmd\");");
                    myWriter.WriteLine("if( objRecord == null ) throw new ArgumentNullException(\"objRecord\");");
                    myWriter.WriteLine(RecordType.FullName + " myRecord = objRecord as " + RecordType.FullName + " ;");
                    myWriter.WriteLine("if( myRecord == null ) throw new ArgumentException(\"must type '" + RecordType.FullName + "' \");");
                    // 更新用SQL语句文本
                    System.Text.StringBuilder myUpdateSQL = new System.Text.StringBuilder();
                    // 所有的SQL参数名称
                    System.Collections.ArrayList ParameterNames = new System.Collections.ArrayList();
                    // 生成类似“字段名1=? , 字段名2=? ”的文本
                    foreach (System.Reflection.PropertyInfo p in ps)
                    {
                        if (p.CanRead == false)
                        {
                            // 属性是不能写则不处理
                            continue;
                        }
                        // 获得对应的数据库字段名
                        string FieldName = GetBindFieldName(p);
                        if (myUpdateSQL.Length > 0)
                        {
                            myUpdateSQL.Append(" , ");
                        }
                        if (myFramework.NamedParameter)
                        {
                            // 使用命名参数模式则输出“字段名 = @Value属性名”。
                            string pName = "Value" + p.Name;
                            ParameterNames.Add(pName);
                            myUpdateSQL.Append(myFramework.FixFieldName(FieldName) + " = @" + pName);
                        }
                        else
                        {
                            // 使用匿名参数模式则输出“字段名 = ?”。
                            myUpdateSQL.Append(myFramework.FixFieldName(FieldName) + " = ? ");
                        }
                    }//foreach
                    ParameterNames.AddRange(KeyParameterNames);
                    // 生成完整的SQL更新语句
                    myUpdateSQL.Insert(0, "Update " + myFramework.FixTableName(TableName) + " Set ");
                    myUpdateSQL.Append(" Where " + myWhereSQL.ToString());
                    // 输出设置SQL命令对象的源代码
                    myWriter.WriteLine("");
                    myWriter.WriteLine("cmd.CommandText = @\"" + myUpdateSQL.ToString() + "\" ;");
                    myWriter.WriteLine("cmd.Parameters.Clear();");
                    myWriter.WriteLine("System.Data.IDbDataParameter parameter = null ;");
                    myWriter.WriteLine("");
                    System.Collections.ArrayList ps2 = new System.Collections.ArrayList();
                    ps2.AddRange(ps);
                    ps2.AddRange(KeyProperties);
                    // 输出填充SQL参数的源代码
                    foreach (System.Reflection.PropertyInfo p in ps2)
                    {
                        if (p.CanRead == false)
                        {
                            // 属性值不能写则不处理
                            continue;
                        }
                        myWriter.WriteLine("");
                        myWriter.WriteLine("parameter = cmd.CreateParameter();");
                        // 输出设置参数值的代码
                        WriteSetParameterValue(p, myWriter);
                        if (myFramework.NamedParameter)
                        {
                            // 若采用命名参数模式则还要设置SQL命令对象的名称
                            myWriter.WriteLine("parameter.ParameterName = \"" + ParameterNames[0] + "\";");
                            // 删除处理过的参数名
                            ParameterNames.RemoveAt(0);
                        }
                        myWriter.WriteLine("cmd.Parameters.Add( parameter );");
                    }//foreach
                    myWriter.WriteLine("");
                    // 返回处理的属性的个数
                    myWriter.WriteLine("return " + ps2.Count + " ;");
                }//else
                myWriter.EndGroup("}//public override int FillUpdateCommand");
                // 结束输出重载 FillUpdateCommand 函数的源代码

                #endregion




                myWriter.EndGroup("}//public class " + RecordType.FullName + "ORMHelper");
                // 结束输出指定类型的ORM帮助器的C#代码

            }//foreach
            myWriter.EndGroup("}//namespace");

            // 若需要保存临时生成的C#代码到指定的文件
            if (strFileName != null && strFileName.Length > 0)
            {
                myWriter.WriteFile(strFileName, System.Text.Encoding.GetEncoding(936));
            }
            // 返回生成的C#代码文本
            return myWriter.ToString();
        }

        /// <summary>
        /// 输出设置SQL参数值的C#源代码文本
        /// </summary>
        /// <param name="p">属性成员</param>
        /// <param name="myWriter">C#代码文本书写器</param>
        private void WriteSetParameterValue(System.Reflection.PropertyInfo p, IndentTextWriter myWriter)
        {
            if (p.PropertyType.Equals(typeof(DateTime)))
            {
                //若属性数据类型为时间型则会调用ORM绑定时指定的WriteFormat格式。
                BindFieldAttribute fa = (BindFieldAttribute)Attribute.GetCustomAttribute(
                    p, typeof(BindFieldAttribute));
                if (fa.WriteFormat == null || fa.WriteFormat.Length == 0)
                {
                    myWriter.WriteLine("parameter.Value = myRecord."
                        + p.Name + ".ToString(\"yyyy-MM-dd HH:mm:ss\");");
                }
                else
                {
                    myWriter.WriteLine("parameter.Value = myRecord."
                        + p.Name + ".ToString(\"" + fa.WriteFormat + "\");");
                }
            }
            else if (p.PropertyType.Equals(typeof(string)))
            {
                // 若属性数据类型为字符串则进行字符串是否为空的处理
                myWriter.WriteLine("if( myRecord." + p.Name + " == null || myRecord."
                    + p.Name + ".Length == 0 )");
                myWriter.WriteLine("   parameter.Value = System.DBNull.Value ;");
                myWriter.WriteLine("else");
                myWriter.WriteLine("   parameter.Value = myRecord." + p.Name + " ;");
            }
            else
            {
                // 直接输出设置SQL参数值的代码文本
                myWriter.WriteLine("parameter.Value = myRecord." + p.Name + " ;");
            }
        }

        /// <summary>
        /// 获得属性成员映射的数据库字段名
        /// </summary>
        /// <param name="p">属性成员</param>
        /// <returns>映射的数据库字段名</returns>
        internal string GetBindFieldName(System.Reflection.PropertyInfo p)
        {
            BindFieldAttribute fa = (BindFieldAttribute)Attribute.GetCustomAttribute(
                p, typeof(BindFieldAttribute));
            string name = fa.Name;
            if (name != null)
                name = name.Trim();
            if (name == null || name.Length == 0)
                name = p.Name;
            return name;
        }

        /// <summary>
        /// 获得指定属性的默认值
        /// </summary>
        /// <param name="p">属性对象</param>
        /// <returns>获得的默认值</returns>
        private object GetDefaultValue(System.Reflection.PropertyInfo p)
        {
            Type pt = p.PropertyType;
            // 获得成员属性附加的 DefaultValueAttribute特性
            System.ComponentModel.DefaultValueAttribute dva =
                (System.ComponentModel.DefaultValueAttribute)
                Attribute.GetCustomAttribute(
                p, typeof(System.ComponentModel.DefaultValueAttribute));
            if (dva == null)
            {
                // 若没有附加特性则根据数据类型返回默认值
                if (pt.Equals(typeof(byte)))
                    return (byte)0;
                else if (pt.Equals(typeof(short)))
                    return (short)0;
                else if (pt.Equals(typeof(int)))
                    return (int)0;
                else if (pt.Equals(typeof(uint)))
                    return (uint)0;
                else if (pt.Equals(typeof(long)))
                    return (long)0;
                else if (pt.Equals(typeof(float)))
                    return (float)0;
                else if (pt.Equals(typeof(double)))
                    return (double)0;
                else if (pt.Equals(typeof(DateTime)))
                    return DateTime.MinValue;
                else if (pt.Equals(typeof(char)))
                    return char.MinValue;
                else
                    return null;
            }
            else
            {
                // 对附加的默认值进行数据类型的转换
                System.ComponentModel.TypeConverter converter =
                    System.ComponentModel.TypeDescriptor.GetConverter(pt);
                if (dva.Value != null)
                {
                    Type t = dva.Value.GetType();
                    if (t.Equals(pt) || t.IsSubclassOf(pt))
                    {
                        return dva.Value;
                    }
                }
                if (converter == null)
                {
                    return dva.Value;
                }
                else
                {
                    return converter.ConvertFrom(dva.Value);
                }
            }
        }
    }
}